import logging
import os
import sys
from logging import handlers
from logging.handlers import TimedRotatingFileHandler

from infra.config_holder import conf

# 日志级别关系映射
LEVEL_MAPPING = {
    'debug': logging.DEBUG,
    'info': logging.INFO,
    'warning': logging.WARNING,
    'warn': logging.WARNING,
    'error': logging.ERROR,
    'critical': logging.CRITICAL
}

# 创建日志对象
app_logger = logging.getLogger(conf['log']['filename'])
# 设置日志级别
app_logger.setLevel(LEVEL_MAPPING.get(conf['log']['level']))
# 日志输出格式
fmt = logging.Formatter('%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s')
# 输出到控制台
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(fmt)
# 输出到文件
# 日志文件按天进行保存，每天一个日志文件
file_handler = handlers.TimedRotatingFileHandler(filename=f"{conf['log']['dir']}/{conf['log']['filename']}",
                                                 when='D',
                                                 backupCount=1,
                                                 encoding='utf-8')
file_handler.setFormatter(fmt)
app_logger.addHandler(console_handler)
app_logger.addHandler(file_handler)


def get_level(level='info'):
    return LEVEL_MAPPING[level]


def time_rotating_file_handler(folder='log', filename='runtime.log', level='info'):
    if not os.path.exists(folder):
        os.mkdir(folder)
    logging_handler = TimedRotatingFileHandler(filename=f"{folder}/{filename}", when='D', backupCount=1,
                                               encoding='utf-8')
    logging_handler.setLevel(LEVEL_MAPPING[level])
    logging_handler.setFormatter(
        logging.Formatter('%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s'))

    return logging_handler


def get_logger(filename: str, level='info'):
    # 创建日志对象
    logger = logging.getLogger(filename)
    # 设置日志级别
    logger.setLevel(LEVEL_MAPPING.get(level))
    # 日志输出格式
    fmt = logging.Formatter('%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s')
    # 输出到控制台
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setFormatter(fmt)
    # 输出到文件
    # 日志文件按天进行保存，每天一个日志文件
    file_handler = handlers.TimedRotatingFileHandler(filename=f"{conf['log']['dir']}/{filename}.log",
                                                     when='D',
                                                     backupCount=1,
                                                     encoding='utf-8')
    file_handler.setFormatter(fmt)

    logger.addHandler(console_handler)
    logger.addHandler(file_handler)

    return logger


def get_app_log():
    return app_logger
